import {routerRedux} from 'dva/router';
import {message} from 'antd';
import { indexGroup, saveIndexGroup, indexGroupDetail, deleteIndexGroup } from '../services/api';

export default {
  namespace: 'indexGroup',
  state: {
    data: [],
    discountData: {}, //促销数据
    group: [],
    detail : {}
  },

  effects: {
    *fetch({payload}, {call, put}){
      const res = yield call(indexGroup, payload);
      if (res) {
        yield put({
          type: 'save',
          payload: {data: res}
        });
      }
    },
    *fetchDetail({payload}, {call, put}){
      const res = yield call(indexGroupDetail, payload);
      if (res) {
        yield put({
          type: 'save',
          payload: {detail: res}
        });
      }
    },
    *changeWeight({payload}, {call, put}){
      const { id, value} = payload;
      const res = yield call(saveIndexGroup, {id,weight:value});
      if (res) {
        yield put({
          type: 'saveWeight',
          payload: payload
        });
      }
    },
    *changeStatus({payload}, {call, put}){
      console.log(payload);
      const res = yield call(saveIndexGroup, payload);
      if (res) {
        yield put({
          type: 'saveStatus',
          payload: payload
        });
      }
    },
    *groupSave({payload}, {call, put}){  //新增与修改
      const res = yield call(saveIndexGroup, payload);
      if (res) {
        return res;
      }
    },
    *deleteItem({payload}, {call, put}){  //删除
      const res = yield call(deleteIndexGroup, payload);
      if (res) {
        yield put({
          type : 'saveDelete',
          payload : payload
        });
        return res;
      }
    },
  },

  reducers: {
    save(state, {payload}){
      return {
        ...state,
        ...payload
      }
    },
    saveWeight(state, {payload}){
      let dataSource = [...state.data];
      const { id, value, dataIndex } = payload;
      const target = dataSource.find(item => item.id === id);
      if (target) {
        target[dataIndex] = value;
      }
      dataSource.sort((a, b)=>{
        return a.weight < b.weight
      });
      return {
        ...state,
        data : dataSource
      }
    },
    saveStatus(state, {payload}){
      let dataSource = [...state.data];
      const { id, status } = payload;
      const target = dataSource.find(item => item.id === id);
      if (target) {
        target.status = status;
      }
      return {
        ...state,
        data : dataSource
      }
    },
    clear(state, {payload}){
      return {
        data: [],
        detail : {},
      }
    },
    saveDelete(state, { payload }){
      let dataSource = [...state.data];
      const target = dataSource.filter(item => item.id != payload.id);
      return {
        ...state,
        data : target
      }
    }
  },
};
